package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-detail/cache"
	"novel-detail/model"
	"time"
)

func List(c *gin.Context) {
	var list []model.Novel

	redis_key := "list"
	CacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if CacheData == "" {
		model.DB.Find(&list)
		jsData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(CacheData), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": list,
	})
	return
}

func Dateil(c *gin.Context) {
	id := c.Query("id")
	var novel model.Novel
	redis_key := "detail_" + id
	model.DB.Where("id=?", id).First(&novel)
	jsData, _ := json.Marshal(novel)
	cache.Rdb.Set(cache.Ctx, redis_key, jsData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取详情成功",
		"data": novel,
	})
	return
}

func Create(c *gin.Context) {

}
func Comment(c *gin.Context) {
	var list []model.Comment

	redis_key := "comment_"
	CacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if CacheData == "" {
		model.DB.Order("Created_at desc").Find(&list)
		jsData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(CacheData), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": list,
	})
	return
}
